﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.Caching;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using System.Xml;
using System.Net;
using System.Text;
using System.IO;

namespace WeatherWebpart.WeatherWebpart
{
    [ToolboxItemAttribute(false)]
    public class WeatherWebpart : WebPart
    {
        protected override void Render(HtmlTextWriter output)
        {
            string location;
            string units;
            string html = string.Empty;
            GetUserLocation(out location, out units);
            try
            {
                XmlDocument xml = GetWeatherData(location, units);
                html = CreateWeatherHtml(xml);
            }
            catch
            {
                html = "<em>Unable to retieve weather at this time</em>";
            }
            output.Write(html);
        }

        private void GetUserLocation(out string location, out string units)
        {
            units = "f";
            try
            {
                SPSite site = SPContext.Current.Site;
                SPServiceContext context = SPServiceContext.GetContext(site);
                UserProfileManager profileMgr = new UserProfileManager(context);
                UserProfile profile = profileMgr.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
                string country = (string)profile["Country"].Value;
                string city = (string)profile["City"].Value;
                location = city + ", " + country;
            }
            catch 
            {
                location = "01760";
            }         
        }

        private string CreateWeatherHtml(XmlDocument xml)
        {
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
            nsmgr.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
            string html = string.Empty;
            XmlNode forcast = xml.SelectSingleNode("/query/results/channel/item/yweather:condition", nsmgr);
            string currTemp = forcast.Attributes["temp"].Value;
            string condcode = forcast.Attributes["code"].Value;
            string description = forcast.Attributes["text"].Value;
            XmlNode title = xml.SelectSingleNode("/query/results/channel/item/title");
            string weatherTitle = title.InnerText;
            XmlNode link = xml.SelectSingleNode("/query/results/channel/item/link");
            string forcastLink = link.InnerText;
            string weatherImageUrl = "http://l.yimg.com/a/i/us/we/52/" + condcode + ".gif";

            html = "<p style=\"margin-top:5px\"><a href=\"" + forcastLink + "\" title=\"Weather Forcast\"><img  alt=\"Weather Image\" align=\"left\" style=\"margin-right:10px;\" width=\"52px\" height=\"52px\" border=\"0\" src=\"" + weatherImageUrl + "\" /></a>";
            html += description + ", " + currTemp + "&deg; in " + weatherTitle.Replace("Conditions for ", "") + "</p>";
            return html;
        }

        private XmlDocument GetWeatherData(string location, string units)
        {
            if (Page.Cache["WeatherXML" + location] == null)
            {
                string query = "select * from weather.forecast where location in (select id from weather.search where query=\"" + location + "\") and u=\"" + units + "\"";
                string yahooURL = "http://query.yahooapis.com/v1/public/yql?format=xml&diagnostics=false&&diagnostics=false&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&q=";
                Uri address = new Uri(yahooURL + query);
                HttpWebRequest request = null;
                HttpWebResponse response = null;
                XmlDocument xmlDoc = null;
                XmlTextReader xmlReader = null;

                try
                {
                    request = (HttpWebRequest)HttpWebRequest.Create(address);
                    request.Method = "GET";
                    request.ContentType = "text/xml; encoding='utf-8'";

                    response = (HttpWebResponse)request.GetResponse();

                    xmlDoc = new XmlDocument();

                    xmlReader = new XmlTextReader(response.GetResponseStream());
                    xmlDoc.Load(xmlReader);
                    Page.Cache.Insert("WeatherXML" + location, xmlDoc, null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    request = null;
                    response = null;
                    xmlReader = null;
                }
            }
            return (XmlDocument)Page.Cache["WeatherXML" + location];
        }
    }
}
